package com.ycj.entropy.fragment;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.ycj.entropy.BrowseStudyActivity;
import com.ycj.entropy.R;
import com.ycj.entropy.data.Study;
import com.ycj.entropy.util.CameraUtil;
import com.ycj.entropy.util.CollectionUtil;
import com.ycj.entropy.util.DateUtil;

import java.util.Date;
import java.util.List;

public class ListItemFragment extends Fragment {

    private Study study;
    private View root;
    private ImageView imageView;
    private TextView txtTitle;
    private TextView txtContent;
    private TextView txtTimeAddress;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        this.root = inflater.inflate(R.layout.fragment_list_item, container, false);
        init();
        return this.root;
    }


    public void setModel(Study study) {
        this.study = study;
    }

    private void init() {
        this.imageView = root.findViewById(R.id.list_item_img);
        this.txtTitle = root.findViewById(R.id.list_item_title);
        this.txtContent = root.findViewById(R.id.list_item_content);
        this.txtTimeAddress = root.findViewById(R.id.list_item_time_address);

        this.txtTitle.setText(this.study.getTitle());
        this.txtContent.setText(this.study.getContent());
        this.txtTimeAddress.setText(DateUtil.format(new Date(this.study.getCreateAt())));

        this.root.setOnClickListener(v -> {
                    Intent intent = new Intent(getActivity(), BrowseStudyActivity.class);
                    intent.putExtra("model", this.study);
                    startActivityForResult(intent,10086);
                }
        );

        List<String> imageList = this.study.imageList();
        if (CollectionUtil.notEmpty(imageList)) {
            String imgName = imageList.get(0);
            Bitmap bitmap = CameraUtil.getImageThumbnail(CameraUtil.storageDir(getActivity()), imgName, 150, 150);
            this.imageView.setImageBitmap(bitmap);
        }
    }
}